/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package queenb.web.controller;

import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import queenb.net.entitybean.M020;
import queenb.web.crm.controller.V030controller;
import queenb.web.crm.store.CustomerStore;
import queenb.web.store.M020Store;
import queenb.web.util.SMSUTIL;
import queenb.web.util.SessionProvider;
import queenb.web.util.Util;

/**
 *
 * @author Nguyen Hung
 */
public class M020Controller extends QueenbController {

    private int pm020;// id M020
    private int fv050;
    private int mn026;
    private int fn100;
    private Date md023F;
    private Date md023T;
    private List<M020> listoftabM020 = new ArrayList<M020>();
    private M020Store m020Store;
    private String tabString;
    private String userchoose;// chon nhan vien

    public M020Controller() {
        m020Store = new M020Store();
        try {
             if(userchoose!=null){
            
        }else{
            userchoose = getLogin().getUserName();
        }
        } catch (Exception e) {
        }
       
        Object action = getRequest().getParameter("action");
        if (action != null) {
            if (action.equals("edit")) {
            }else if(action.equals("getidreadfile")){
                Object objpm020 = getRequest().getParameter("pm020");
                if(objpm020!=null){
                    pm020 = Util.parseInt(objpm020);
                }
                System.out.println("-------------PM020---------"+pm020);
            }else if(action.equals("chooseEmp")){
                Object objpm020 = getRequest().getParameter("name");
                if(objpm020!=null){
                    userchoose = objpm020.toString();
                }
                System.out.println("-----------USER LOGIN--------"+userchoose);
                SessionProvider.setSessionMapValue("userchoose",userchoose);
            }
        }
    }

    public void searchdataM020() {
        try {
            System.out.println(md023T + "---------DATE----------------------------------------" + md023F);
        } catch (Exception e) {
        }
    }

    public void onchangeM020() {
        try {
            System.out.println("----------VN026------" + mn026);
        } catch (Exception e) {
        }
    }

    /**
     * @return the pm020
     */
    public int getPm020() {
        return pm020;
    }

    /**
     * @param pm020 the pm020 to set
     */
    public void setPm020(int pm020) {
        this.pm020 = pm020;
    }

    /**
     * @return the fv050
     */
    public int getFv050() {
        return fv050;
    }

    /**
     * @param fv050 the fv050 to set
     */
    public void setFv050(int fv050) {
        this.fv050 = fv050;
    }

    /**
     * @return the mn026
     */
    public int getMn026() {
        return mn026;
    }

    /**
     * @param mn026 the mn026 to set
     */
    public void setMn026(int mn026) {
        this.mn026 = mn026;
    }

    /**
     * @return the fn100
     */
    public int getFn100() {
        return fn100;
    }

    /**
     * @param fn100 the fn100 to set
     */
    public void setFn100(int fn100) {
        this.fn100 = fn100;
    }

    /**
     * @return the md023F
     */
    public Date getMd023F() {
        return md023F;
    }

    /**
     * @param md023F the md023F to set
     */
    public void setMd023F(Date md023F) {
        this.md023F = md023F;
    }

    /**
     * @return the md023T
     */
    public Date getMd023T() {
        return md023T;
    }

    /**
     * @param md023T the md023T to set
     */
    public void setMd023T(Date md023T) {
        this.md023T = md023T;
    }

    /**
     * @return the listoftabM020
     */
    // read fiel sms
    public void readsmsforFibo(){
        try {
            System.out.println("============UPDATE---"+pm020);
            if(pm020!=0){
                CustomerStore customerStore = new CustomerStore();
                int count = customerStore.updateColumnN100(null,"M020","MV031", "C", "PM020", pm020, getLogin().getUserName());
                System.out.println("------------AAAAAAAAAAACOUNT---"+count);
            }
        } catch (Exception e) {
        }
    }
    public List<M020> getListoftabM020() {
        try {
            V030controller v030 = new V030controller();
           
            if(SessionProvider.getSessionMapValue("userchoose")!=null){
                userchoose = SessionProvider.getSessionMapValue("userchoose").toString();
            }
             System.out.println("-------LIST SMS--------" + getLogin().getModule() + "," + getLogin().getCompanyNo() + "," + v030.getFV050() + "," + fn100 + "," + Util.toSQLDate(md023F) + "," + Util.toSQLDate(md023T) + "," + mn026 + "," + userchoose);
            listoftabM020 = m020Store.mcurpks_listoftabm020(getLogin().getModule(), getLogin().getCompanyNo(), 0, v030.getFV050(), fn100, "B", Util.toSQLDate(md023F), Util.toSQLDate(md023T), mn026, userchoose);
            return listoftabM020;
        } catch (Exception e) {
            return null;
        }
    }

    public List<M020> getListoftabM020Receive() {
        try {
          
               listoftabM020 = m020Store.mcurpks_listoftabm020Re( "A", getLogin().getUserName());
           
            
            return listoftabM020;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @param listoftabM020 the listoftabM020 to set
     */
    public void setListoftabM020(List<M020> listoftabM020) {
        this.listoftabM020 = listoftabM020;
    }

    public void chooseTabrsms() {
        try {
            setTabString("TABRSMS");
            SessionProvider.setSessionMapValue("TABNTG", tabString);
        //    updateSMSreceiveforFibo();
        } catch (Exception e) {
        }
    }
// Xóa hết SMS
    
    public void deleteSMS(){
        try {
            List<M020> list =m020Store.mcurpks_listoftabm020Re( "A", getLogin().getUserName());
            System.out.println("-------"+list.size());
            if(list!=null){
                for(int i=0;i<list.size();i++){
                     int count = m020Store.stdm_tools_stornotabm020(list.get(i).getPm020(), getLogin().getUserName());
                     System.out.print("----------------COUNT-------"+count);
                }
               
            }
        } catch (Exception e) {
        }
    }
    public void chooseTabssms() {
        try {
            setTabString("TABSSMS");
            SessionProvider.setSessionMapValue("TABNTG", tabString);
        } catch (Exception e) {
        }
    }

    /**
     * @return the tabString
     */
    public String getTabString() {
        if (SessionProvider.getSessionMapValue("TABNTG") != null) {
            tabString = SessionProvider.getSessionMapValue("TABNTG").toString();
        } else {
        }
        return tabString;
    }

    /**
     * @param tabString the tabString to set
     */
    public void setTabString(String tabString) {
        this.tabString = tabString;
    }
    
//     public static void main(String[] args) {
//         updateSMSreceiveforFibo();
//     }

    public void updateSMSreceiveforFibo() {

        String formid = "568814";
        Long longid = Long.valueOf(formid);
        String abc = SMSUTIL.reviceSMSofCustomer(longid);
        final String xmlStr = abc;
        Document doc = convertStringToDocument(xmlStr);
        String str = convertDocumentToString(doc);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        DocumentBuilder builder;
        try {
            builder = factory.newDocumentBuilder();

            // Use String reader  
            Document document = builder.parse(new InputSource(new StringReader(str)));

            TransformerFactory tranFactory = TransformerFactory.newInstance();
            Transformer aTransformer = tranFactory.newTransformer();
            Source src = new DOMSource(document);
            Result dest = new StreamResult(new File("D:\\file.xml"));
            aTransformer.transform(src, dest);
            readerfileXMLforSystem("D:\\file.xml");
        } catch (Exception e) {
            // TODO Auto-generated catch block  
            e.printStackTrace();
        }

    }

    // Doc file XML
    private static String convertDocumentToString(Document doc) {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer;
        try {
            transformer = tf.newTransformer();
            // below code to remove XML declaration
            // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(doc), new StreamResult(writer));
            String output = writer.getBuffer().toString();
            return output;
        } catch (TransformerException e) {
            e.printStackTrace();
        }

        return null;
    }

    private static Document convertStringToDocument(String xmlStr) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;
        try {
            builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new InputSource(new StringReader(xmlStr)));
            return doc;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // DOC FILE XML SAVE DB
    public  void readerfileXMLforSystem(String file) {
        try {
            File fXmlFile = new File(file);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            //optional, but recommended
            //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
            doc.getDocumentElement().normalize();
            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
            NodeList nList = doc.getElementsByTagName("SMSLIST");
            System.out.println("----------------------------");
            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);
                System.out.println("\nCurrent Element :" + nNode.getNodeName());
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    System.out.println("ClientCommingSMSID :-------------- " + eElement.getElementsByTagName("ClientCommingSMSID").item(0).getTextContent());
                    System.out.println("PhoneNumber :---------------- " + eElement.getElementsByTagName("PhoneNumber").item(0).getTextContent());
                    System.out.println("message -----------------: " + eElement.getElementsByTagName("message").item(0).getTextContent());
                    System.out.println("SentDate :--------------------- " + eElement.getElementsByTagName("SentDate").item(0).getTextContent());
//                    String text = eElement.getElementsByTagName("SentDate").item(0).getTextContent();
//                    SimpleDateFormat formatter, FORMATTER;
//                    formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
//                   
//                    Date date = formatter.parse(text.substring(0, 24));
//                    FORMATTER = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss.SSS");
//                    System.out.println("OldDate-->" + text);
//                    System.out.println("NewDate-->" + FORMATTER.format(date));
                    System.out.println("ClientCommingSMSHostingStatus :--------------------- " + eElement.getElementsByTagName("ClientCommingSMSHostingStatus").item(0).getTextContent());
                    System.out.println("createddate :--------------------- " + eElement.getElementsByTagName("createddate").item(0).getTextContent());
                    System.out.println("ServiceTypeID :--------------------- " + eElement.getElementsByTagName("ServiceTypeID").item(0).getTextContent());
                    System.out.println("serviceTypename :--------------------- " + eElement.getElementsByTagName("serviceTypename").item(0).getTextContent());
                    String datesms = eElement.getElementsByTagName("SentDate").item(0).getTextContent().substring(0, 10);
                    String abc = datesms.substring(8,10)+"/"+datesms.substring(5,7)+"/"+datesms.substring(0,4);
                  SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
                    Date convertedDate = dateFormat.parse(abc); 
    
                     System.out.println(Util.toSQLDate(convertedDate)+"----DATE------"+abc);
                    int count = m020Store.stdm_tools_inserttabm020(pm020, eElement.getElementsByTagName("PhoneNumber").item(0).getTextContent(), eElement.getElementsByTagName("message").item(0).getTextContent(), "A", Util.toSQLDate(convertedDate), Util.toSQLDate(convertedDate), "", 1, 0, 0, 0,eElement.getElementsByTagName("ClientCommingSMSID").item(0).getTextContent(),"O", getLogin().getUserName());
                    System.out.println(count+"-----------READ SMS FOR FIBO--------"+pm020+","+ eElement.getElementsByTagName("PhoneNumber").item(0).getTextContent()+","+eElement.getElementsByTagName("message").item(0).getTextContent()+","+ "A"+","+ Util.toSQLDate(new Date())+","+ Util.toSQLDate(new Date())+","+ ""+","+ 1+","+ 0+","+ 0+","+ 0+","+eElement.getElementsByTagName("ClientCommingSMSID").item(0).getTextContent()+","+ getLogin().getUserName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @return the userchoose
     */
    public String getUserchoose() {
        if(SessionProvider.getSessionMapValue("userchoose")!=null){
                userchoose = SessionProvider.getSessionMapValue("userchoose").toString();
            }
        return userchoose;
    }

    /**
     * @param userchoose the userchoose to set
     */
    public void setUserchoose(String userchoose) {
        this.userchoose = userchoose;
    }
}
